package com.jshoperxms.components.netease.im;

import com.jshoperxms.components.netease.CheckSumBuilder;
import com.jshoperxms.components.netease.JPNeteaseKey;
import com.jshoperxms.components.netease.bean.LiveChannelBean;
import com.jshoperxms.controller.utils.json.GsonJson;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * Created by sdywcd on 2018/5/29.
 * Des:
 */
@Component
public class NeteaseLiveController {

    //随机数
    private static final String NONCE="00112233445566778899";


    public LiveChannelBean createLiveChannel(String roomname) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost=new HttpPost(LiveUrl.createChannel);
        String curTime=String.valueOf((new Date()).getTime()/1000L);
        String checkSum= CheckSumBuilder.getCheckSum(JPNeteaseKey.SECRET,NONCE,curTime);
        // 设置请求的header
        httpPost.addHeader("AppKey", JPNeteaseKey.APPKEY);
        httpPost.addHeader("Nonce", NONCE);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        // 设置请求的参数
        // 设置请求的参数
        StringEntity params = new StringEntity("{\"name\":\""+roomname+"\", \"type\":0}", Consts.UTF_8);
        httpPost.setEntity(params);
        // 执行请求
        HttpResponse response = httpclient.execute(httpPost);
        // 打印执行结果
        LiveChannelBean liveChannelBean= GsonJson.parsejsonToObject(EntityUtils.toString(response.getEntity(),"utf-8"),LiveChannelBean.class);
        return liveChannelBean;
    }
}
